package com.exercise.storage.api;


import com.exercise.commons.param.BasePageParam;
import com.exercise.commons.po.ProductDO;
import com.exercise.commons.utils.UUIDUtils;
import com.exercise.commons.vo.Paging;
import com.exercise.commons.vo.Product;
import com.exercise.storage.mapper.ProductMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductServiceApi {

    @Autowired
    private ProductMapper productMapper;

    @RequestMapping("/save")
    public int save(Product product) {

        if (StringUtils.isBlank(product.getId())) {
            product.setId(UUIDUtils.getUUID());
            return productMapper.insert(new ProductDO(product));
        }

        return productMapper.updateByPrimaryKey(new ProductDO(product));
    }


    @RequestMapping("/get")
    public Product get(String productId) {

        if(StringUtils.isBlank(productId)){
            return null;
        }
        return productMapper.selectByPrimaryKey(productId).convertToModel();
    }

    @RequestMapping("/pageQueryProduct")
    public Paging<Product> pageQueryProduct(BasePageParam param) {

        Paging<Product> result = new Paging<>();
        if (param == null) {
            return result;
        }

        if (param.getPagination() < 0) {
            param.setPagination(0);
        }

        if (param.getPageSize() < 0) {
            param.setPageSize(10);
        }

        //查询数据总数
        int counts = productMapper.selectAllCounts();
        if (counts < 0) {
            return result;
        }

        //组装返回数据
        result.setTotalCount(counts);
        result.setPageSize(param.getPageSize());
        result.setPageNum(param.getPagination());

        int totalPage = (int)Math.ceil(counts / (param.getPageSize() * 1.0));
        result.setTotalPage(totalPage);

        //实际返回的数据
        List<ProductDO> productDOS = productMapper.pageQuery(param);
        List<Product> productList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(productDOS)) {
            for (ProductDO productDO : productDOS) {
                productList.add(productDO.convertToModel());
            }
        }

        result.setData(productList);

        return result;
    }
}
